<template>
  <div class="container" style="height: 100%">
    <div class="flex_cm" style="height: 100%">
      <search
        :form_data="header_list"
        @changeIsShow="
          (e) => {
            header_list[e].isShow = !header_list[e].isShow
          }
        "
        @search="search_key"
        @reset="
          header_list.forEach((item) => {
            item.value = ''
          }),
            search_key()
        "
      ></search>
      <div class="p_0_10 bg_fff flex1">
        <div class="flex_js p_10_0">
          <div class="c_666 fw">项目列表</div>
          <div class="flex">
            <el-button
              type="primary"
              @click="show_box = true"
              v-if="has_role_list[0].has_role"
              >新增</el-button
            >
            <setTable
              :data="header_list"
              :height_size="height_size"
              @changeShowTable="
                (e) => {
                  header_list[e].showTable = !header_list[e].showTable
                }
              "
              @resetTableSet="
                () => {
                  header_list.forEach((item) => {
                    item.showTable = true
                  })
                }
              "
              @changeHeightSize="
                (e) => {
                  height_size = e
                }
              "
            ></setTable>
          </div>
        </div>
        <el-table
          style="text-align: center"
          :data="list"
          :max-height="max_height"
          border
          v-loading="loading"
          :default-sort="{ prop: 'createTime' }"
          :row-style="{
            height: height_size == 2 ? '50px' : '',
          }"
          :cell-style="{
            padding: height_size == 3 ? '0' : '',
          }"
        >
          <el-table-column
            type="index"
            label="序号"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="名称"
            prop="name"
            key="名称"
            sortable
            v-if="header_list[0].showTable"
          ></el-table-column>
          <el-table-column
            label="代号"
            prop="code"
            key="代号"
            sortable
            v-if="header_list[1].showTable"
          ></el-table-column>
          <el-table-column
            label="负责人"
            key="负责人"
            sortable
            prop="leaderId"
            v-if="header_list[2].showTable"
          >
            <template #default="scope: any">
              <div v-for="item in member_list" :key="item.id">
                <span v-if="item.memberId == scope.row.leaderId">{{
                  item.name
                }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            key="状态"
            sortable
            prop="isDelete"
            v-if="header_list[3].showTable"
            ><template #default="scope: any">
              <div v-if="scope.row.isDelete">回收站</div>
              <div v-else style="color: #3580eb">进行中</div></template
            ></el-table-column
          >
          <el-table-column label="操作" v-if="has_role_list[0].has_role">
            <template #default="scope: any">
              <el-button @click="edit_list(scope)">编辑</el-button>
              <el-button v-if="!scope.row.isDelete" @click="delete_list(scope)"
                >删除</el-button
              >
              <el-button v-else @click="delete_list(scope)">还原</el-button>
              <el-button type="primary" @click="to_engineer_list(scope)"
                >工程列表</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="m_10_0 pagination"
          v-model:current-page="page_data.current"
          v-model:page-size="page_data.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="list_debounce()"
          @current-change="list_debounce()"
        />
      </div>
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      size="70%"
      destroy-on-close
      @close="resetForm(addProform)"
      :close-on-click-modal="false"
    >
      <template #title>
        <h4 v-if="add_form_data.id == ''">新增项目</h4>
        <h4 v-else>编辑项目</h4>
      </template>
      <template #default>
        <el-form
          ref="addProform"
          :model="add_form_data"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="项目名称" prop="name">
            <el-input
              v-model="add_form_data.name"
              placeholder="请输入"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="项目代号" prop="code">
            <el-input
              v-model="add_form_data.code"
              placeholder="请输入"
              show-word-limit
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="项目负责人" prop="leaderId">
            <el-select
              v-model="add_form_data.leaderId"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in member_list"
                :key="item.memberId"
                :value="item.memberId"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <div class="tr m_top10">
            <el-button @click="resetForm(addProform)">取消</el-button>
            <el-button @click="submit_pro(addProform)" type="primary"
              >确认</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>
<script lang="ts">
export default {
  name: 'szlsProList',
}
</script>
<script lang="ts" setup>
import { check_role, debounce, handle_search_key } from '@/utils/check_role' // 权限校验
import search from '@/view/components/search.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, onUnmounted, computed } from 'vue'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { FormInstance, ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from 'vuex'
const store = useStore()
const has_role_list = ref([{ path: 'szlsProject/post', has_role: false }])
// type FormInstance = InstanceType<typeof ElForm>
const addProform = ref<FormInstance>()
const rules = ref({
  // 表单验证规则
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入项目代号', trigger: 'blur' }],
  enterpriseId: [
    { required: true, message: '请选择归属企业', trigger: 'change' },
  ],
  leaderId: [
    { required: true, message: '请选择项目负责人', trigger: 'change' },
  ],
})
const list = ref()
const total = ref()
const loading = ref(false)
const show_box = ref(false)
const height_size = ref(1)
const header_list = ref([
  {
    label: '名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '代号',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '负责人',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '状态',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: [
      {
        value: '0',
        label: '进行中',
      },
      {
        value: '1',
        label: '回收站',
      },
    ],
  },
])

const page_data = ref({
  current: 1,
  pageSize: 10,
  name: '',
  code: '',
  isDelete: '',
  //   enterpriseName: '',
  leader: '',
  enterpriseId: computed(() => {
    return store.state.enterprise_id
  }),
})
const add_form_data = ref({
  id: '',
  name: '',
  code: '',
  leaderId: '',
  enterpriseId: computed(() => {
    return store.state.enterprise_id
  }),
})
const max_height = ref()
onMounted(() => {
  max_height.value = window.innerHeight - 320 // 带分页的 table 高度
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('刷新成功！')
  })
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item)
  })
  console.log(store.state.check_role_list)
  console.log(has_role_list.value)
  get_list()
  get_member_list()
})
onUnmounted(() => {
  EventBus.off('refresh')
})
const to_engineer_list = (e) => {
  console.log(e)
  EventBus.emit('list_change', 2)
  setTimeout(() => {
    EventBus.emit('projectId', e.row.id)
  })
}
const delete_list = (e) => {
  ElMessageBox.confirm(
    e.row.isDelete ? '确定还原：' + e.row.name : '确定删除：' + e.row.name,
    '',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      type: 'error',
    }
  )
    .then(() => {
      axios
        .request({
          url: !e.row.isDelete
            ? serviceApi.szls_project_crud + '/' + e.row.id
            : serviceApi.szls_project_restore + '/' + e.row.id,
          method: !e.row.isDelete ? 'delete' : 'put',
        })
        .then(() => {
          ElMessage.success('操作成功！')
          setTimeout(() => {
            get_list()
          }, 1000)
        })
        .catch((err) => {
          ElMessage.error(err)
        })
    })
    .catch(() => {})
}
const edit_list = (e) => {
  add_form_data.value = {
    id: e.row.id,
    name: e.row.name,
    code: e.row.code,
    leaderId: e.row.leaderId,
    enterpriseId: add_form_data.value.enterpriseId,
  }
  get_member_list()
  show_box.value = true
}
const btn_loading = ref(false)
const submit_pro = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return
      btn_loading.value = true
      axios
        .request({
          url:
            add_form_data.value.id == ''
              ? serviceApi.szls_project_crud
              : serviceApi.szls_project_crud + '/' + add_form_data.value.id,
          method: add_form_data.value.id == '' ? 'post' : 'put',
          data: add_form_data.value,
        })
        .then(() => {
          ElMessage.success('操作成功！')
          setTimeout(() => {
            btn_loading.value = false
            resetForm(formEl)
            get_list()
            show_box.value = false
          }, 1000)
        })
        .catch((err) => {
          ElMessage.error(err)
          btn_loading.value = false
        })
    }
  })
}
const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.szls_project_list,
      method: 'post',
      data: page_data.value,
    })
    .then((res) => {
      console.log(res)
      res.data.content.forEach((item) => {
        item.hasChildren = true
        item.children = []
      })
      list.value = res.data.content
      total.value = parseInt(res.data.totalElements)
      loading.value = false
    })
    .catch((err) => {
      ElMessage.error(err)
      loading.value = false
    })
}
const member_list = ref()
const member_page_data = ref({
  enterpriseId: add_form_data.value.enterpriseId,
  current: 1,
  pageSize: 10000,
  name: '',
  status: 2,
})
const get_member_list = () => {
  axios
    .request({
      url: serviceApi.user_list,
      method: 'post',
      data: handle_search_key(member_page_data.value),
    })
    .then((res) => {
      console.log(res)
      member_list.value = res.data.content
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
let list_debounce = debounce(200, get_list)
const search_key = () => {
  console.log(header_list.value)
  page_data.value.name = header_list.value[0].value
  page_data.value.code = header_list.value[1].value
  //   page_data.value.enterpriseName = header_list.value[2].value
  page_data.value.leader = header_list.value[2].value
  page_data.value.isDelete =
    header_list.value[3].value == ''
      ? ''
      : header_list.value[3].value == '1'
      ? (true as any)
      : (false as any)
  get_list()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    id: '',
    name: '',
    code: '',
    leaderId: '',
    enterpriseId: '',
  }
  show_box.value = false
}
</script>

<style lang="scss" scoped></style>
